package com.haierp.controller;


import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.io.FileUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import com.haierp.model.WxMessageItem;
import com.haierp.service.IWxUploadMessageService;
import com.haierp.service.impl.UploadFileServiceImpl;
import com.haierp.util.JsonPageResult;
import com.haierp.util.JsonResult;
import com.haierp.vo.PageQueryVO;
import com.wangzhixuan.commons.base.BaseController;


@Controller
@RequestMapping("/wx")
public class WxGroupMessageController extends BaseController{
	
	
	@Autowired
	private IWxUploadMessageService wxUploadMessageService;
	
	@Autowired
	private UploadFileServiceImpl uploadFileService;
	
	@RequestMapping("/uploadMessage")
	@ResponseBody
	public Object uploadMessage(WxMessageItem messageItem ) {
		JsonResult<String> result = new JsonResult<>();
		try {
			Date time = new Date();
			messageItem.setGmtCreate(time);
			messageItem.setGmtModify(time);
			
			String sendTime = messageItem.getMessageTime();
		    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");  
		    Date date = sdf.parse(sendTime);  
		    messageItem.setSendTime(date);
		    
			wxUploadMessageService.insert(messageItem);
		} catch(Exception e) {
			e.printStackTrace();
			return result.buildIsSuccess(false).buildMsg("保存数据失败");
			
		}
		return result.buildIsSuccess(true).buildMsg("接收数据成功");
	}
	
	
	@RequestMapping("/uploadMessImage")
	@ResponseBody
	public Object uploadMessImage(String messageId, String imageUrl) {
		JsonResult<String> result = new JsonResult<>();
		
		try {
			WxMessageItem item = new WxMessageItem();
			item.setMessageId(messageId);
	
			WxMessageItem selectItem = wxUploadMessageService.selectOne(item);
			if(selectItem != null) {
				if(selectItem.getMessageType() != null && selectItem.getMessageType().equalsIgnoreCase("picture")) {
					item.setMessageContent(imageUrl);
					item.setGmtModify(new Date());
					item.setId(selectItem.getId());
					wxUploadMessageService.updateSelectiveById(item);
				} else {
					return result.buildIsSuccess(false).buildMsg("没有需要更新的数据");
				}
			} else {
				return result.buildIsSuccess(false).buildMsg("没有需要更新的数据");
			}
		}catch(Exception e){
			e.printStackTrace();
			return result.buildIsSuccess(false).buildMsg("数据更新失败");
		}
		return result.buildIsSuccess(true).buildMsg("接收数据更新成功");
	}
	
	@RequestMapping("/incomingGroupRecord")
	@ResponseBody
	public Object incomingGroupRecord() throws FileNotFoundException {
		JsonResult<String> result = new JsonResult<String>();
		String filePath = "C:\\Users\\Administrator\\Desktop\\message";
		String str = null;
		//String pathStr = filePath+"aaa_第"+index+"页.html";
		File dirFile =  new File(filePath);
		File[] fileList = dirFile.listFiles();
		for (File file : fileList) {
			if (file.isDirectory()) {
				continue;
			}
			long startTime = System.currentTimeMillis();    //获取开始时间
			
			try {
				str = FileUtils.readFileToString(file, "UTF-8");
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
	        Document doc = Jsoup.parse(str);
	        //System.out.println(doc.toString());
	        Elements content = doc.select("div.chatItemContent");
	        List<WxMessageItem> list = new ArrayList<WxMessageItem>();
	        for (Element link : content) {
	        	WxMessageItem wxMessageItem = new WxMessageItem();
	        	String timeStr = null;
	            Elements times = link.getElementsByClass("timeyou");
	            Date d = null;
	            Element time = times.get(0);
                timeStr = time.text();
				try {
					d = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(timeStr);
				} catch (ParseException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
                wxMessageItem.setSendTime(d);
	
	            Elements clouds = link.getElementsByClass("cloudContent");
	            Element cloud = clouds.get(0);
                String cloudStr = cloud.text();
                Elements srcs =  cloud.getElementsByTag("img");
                String imgSrcStr = "";
                for (int i  = 0  ; i < srcs.size(); i++ ) {
                    String temp = srcs.get(i).attr("src")+" ";
                    imgSrcStr = temp+imgSrcStr;
                }
                String message = cloudStr+imgSrcStr;
                if (!message.contains("：")) {
                	wxMessageItem.setMessageContent(message);
                	wxMessageItem.setGmtCreate(new Date());
                    wxMessageItem.setGmtModify(new Date());
                } else {
                	String name = message.substring(0,message.indexOf("："));
                    String msgContent = message.substring(message.indexOf("：")+1,message.length());
                    if (msgContent.contains("Img")) {
                    	msgContent.trim();
                    	//msgContent = uploadImg(filePath+"\\"+msgContent, String.valueOf(d.getTime()));
                    	wxMessageItem.setMessageType("picture");
                    }
                    wxMessageItem.setFromUserName(name);
                    wxMessageItem.setMessageContent(msgContent);
                    wxMessageItem.setGmtCreate(new Date());
                    wxMessageItem.setGmtModify(new Date());
                }
                
                WxMessageItem tjWxMessageItem = new WxMessageItem();
                tjWxMessageItem.setSendTime(wxMessageItem.getSendTime());
                WxMessageItem sel = wxUploadMessageService.selectOne(tjWxMessageItem);
                if(sel == null) {
                	if (wxMessageItem.getMessageType() == "picture") {
                		String msgContent = uploadImg(filePath+"\\"+wxMessageItem.getMessageContent(), String.valueOf(d.getTime()));
                		wxMessageItem.setMessageContent(msgContent);
                	}
                	list.add(wxMessageItem);
                } else {
                	System.out.println(wxMessageItem.getSendTime());
                }
	        }
	        if(list.size() >0 ) {
	        	wxUploadMessageService.insertBatch(list);
	        }
	        long endTime = System.currentTimeMillis();    //获取结束时间
	        System.out.println("程序运行时间：" + (endTime - startTime) + "ms");    //输出程序运行时间
	        
		}
        //System.out.println(content.toString());
		return result;
	}
	
	public String uploadImg(String path , String key) throws FileNotFoundException {
		File file = new File(path);
		InputStream inputStream = new FileInputStream(file);
		String url = uploadFileService.uploadImg(inputStream, key);
		return url;
	}
	
	@RequestMapping("/messageList")
	public String messageList(PageQueryVO pageQueryVO) {
		HttpServletRequest request = ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest();
		if(request.getParameter("pageSize") == null) {	//当参数没设置pageSize时，默认700
			pageQueryVO.setPageSize(700);
		}
		
		JsonPageResult<List<WxMessageItem>> result = new JsonPageResult<List<WxMessageItem>>();
		result = wxUploadMessageService.queryWxMessageItem(pageQueryVO);
		request.setAttribute("count", result.getTotalCount());
		request.setAttribute("totalPage", result.getTotalPage());
		request.setAttribute("pageIndex", result.getPageIndex());
		request.setAttribute("wxMessageItemList", result.getData());
		request.setAttribute("pageSize", pageQueryVO.getPageSize());
		
		if(request.getParameter("pageIndex") == null) {
			return "redirect:messageList?pageIndex=" + result.getTotalPage() + "&pageSize=" + pageQueryVO.getPageSize();
		} else {
			return "haierp/wxMessageItemList";
		}
	}
	
	@RequestMapping("/updateWxMessageSignByIds")
	@ResponseBody
	public void updateWxMessageSignByIds(String ids) {
		wxUploadMessageService.updateWxMessageSignByIds(ids);
	}
}
